//
//  NSConditionLockDemo.m
//  MultiperThreadTest02
//
//  Created by FelixYin on 2020/4/5.
//  Copyright © 2020 FelixYin. All rights reserved.
//

#import "NSConditionLockDemo.h"

@interface  NSConditionLockDemo()

//条件锁功能 更多普通加锁，条件加锁
@property (nonatomic,strong) NSConditionLock *dataLock;
@property (nonatomic,strong) NSMutableArray *dataArray;

@end

@implementation NSConditionLockDemo

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.dataLock = [[NSConditionLock alloc] initWithCondition:1];
        self.dataArray = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)test {
    [[[NSThread alloc] initWithTarget:self selector:@selector(remove) object:nil] start];
    sleep(4);
    [[[NSThread alloc] initWithTarget:self selector:@selector(add) object:nil] start];
}


//添加数据
- (void) add{
    [self.dataLock lockWhenCondition:1];
    NSLog(@"添加元素");
    [self.dataArray addObject:@"数据"];

    [self.dataLock unlockWithCondition:2];
    
    NSLog(@"发送条件信号");
}

//移除最后一个数据
- (void) remove{
    [self.dataLock lockWhenCondition:2];
    if (self.dataArray.count == 0) {
        //当不满足条件时
        NSLog(@"等待条件");
    }
    NSLog(@"删除元素");
    [self.dataArray removeLastObject];
//    [self.dataLock unlockWithCondition:1];
    [self.dataLock unlock];
}

@end
